/*
 Copyright (c) 2008 TPSi
 Alex Iskander
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 
 */

#ifndef BINDABLE_BINDABLE_FUNCTIONS_SETTERS_BOUNDSETTERFUNCTION_H_
#define BINDABLE_BINDABLE_FUNCTIONS_SETTERS_BOUNDSETTERFUNCTION_H_

#define BIND_SETTER(type,object,targetType,function) \
new Bind::BoundSetterFunction<type, targetType>(object, &targetType::function)

#include "../SetterFunction.h"

namespace Bind
{
	
	template <class Type, class Target> 
	class BoundSetterFunction : public Bind::SetterFunction<Type>
	{
	public:
		typedef void (Target::*FunctionPointer) (Type value); // the function type
		
		
		/**
		 \fn BoundSetterFunction(
		 Target &target, 
		 BoundSetterFunction<Type, Target>::FunctionPointer f
		 );
		 \brief Creates a new bound setter function (a closure for a setter).
		 
		 \e target corresponds to the object on which to apply the function; f
		 corresponds to the object 
		 */
		BoundSetterFunction(
							Target &target,
							typename BoundSetterFunction<Type, Target>::FunctionPointer f
							);
		
		/**
		 \fn operator() (Bindable *This, Type value);
		 \brief The function itself. Calls the function represented.
		 */
		void operator() (Bindable *This, Type value);
		
		Target *target; //!< The object to apply the function to.
		FunctionPointer f; //!< The function pointer.
	};
	
	
	template <class Type, class Target> inline void
	BoundSetterFunction<Type, Target>::operator() (Bindable *This, Type value)
	{
		//return the result of executing the function
		return (target->*f)(value);
	}
	
	template <class Type, class Target>
	BoundSetterFunction<Type, Target>::BoundSetterFunction(
														   Target &target,
														   typename BoundSetterFunction<Type, Target>::FunctionPointer f
														   )
	{
		this->f = f;
		this->target = &target;
	}
	
	
	template<class R, class T> 
	BoundSetterFunction<R, T> *setter(T *object, void (T::*f) (R value))
	{
		return new Bind::BoundSetterFunction<R, T>(*object, f);
	}
}

#endif

